package com.huluobo.a2211mdmdemo.myViews

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.LinearInterpolator
import kotlinx.coroutines.runBlocking

/**
 *  Created by LC on 2025/5/9.
 *  1个参的构造方法一般用于在代码中创建一个View,比如在布局上展示一个礼物
 *  2个参的构造方法一般用于xml中创建一个View,attributeSet 属性集合,自带宽高属性,保存在结合当中
 *  3个参数和四个参数的不常用,第三个参数和第四个参数都是Style文件
 */
class MyView(context: Context) : View(context) {

    //测量 widthMeasureSpec 都包含一个mode和一个size,mode代表测量的模式,比如MathParent,warpContent,size就是具体的大小
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    //摆放 View中摆放View的位置,一般单独的View不会使用这个方法,只有在ViewGroup中才会使用,View中没有其他的View
    // left: Int, top: Int, right: Int, bottom: Int 分别代表距离左侧顶点的位置
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
    }


    //画笔
    private lateinit var paint: Paint
    private lateinit var paintText: Paint

    //绘制的角度
    private var progress = 0f

    private var num = 5

    init {
        initPaint()
        start()
    }

    private fun initPaint() {
        paint = Paint()
        paintText = Paint()
        paint.color = Color.RED
        paintText.color = Color.BLACK
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 5f
        paintText.textSize = 100f
    }

    //绘制方法,canvas 画布,所有的呈现的view的形状都在画布上,比如view是一个圆,是一段文字
    //参数中的100并不是dp 而是px
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val rectF = RectF(100f, 100f, 600f, 600f)
//        canvas.drawRect(rectF, paint)
        canvas.drawArc(rectF, 270f, progress, false, paint)
        canvas.drawText(num.toString(), 320f, 380f, paintText)
    }

    fun start() {
        runBlocking {
            val animator = ValueAnimator.ofFloat(0f, 360f)
            animator.addUpdateListener {
                progress = it.animatedValue as Float
                //绘制自身
                invalidate()
            }
            animator.interpolator = LinearInterpolator()
            animator.duration = 5000
            animator.start()
        }

        runBlocking {
            val animatorText = ValueAnimator.ofInt(num, 0)
            animatorText.addUpdateListener {
                num = it.animatedValue as Int
                invalidate()
            }
            animatorText.interpolator = LinearInterpolator()
            animatorText.duration = num * 1000L
            animatorText.start()
        }
    }
}